/* ************************************************************************
> File Name:     binarytree.c
> Author:        zhfu
> mail:          3346897597@qq.com
> Created Time:  2022年05月04日 星期三 10时54分13秒
> Description:   
 ************************************************************************/
#include<stdlib.h>
#include"binarytree.h"

static link make_node(unsigned char item)
{
    link p = malloc(sizeof *p);
    p->item = item;
    p->l = NULL;
    p->r = NULL;

    return p;
}

static void free_node(link p)
{
    free(p);
    p = NULL;
}

link init(unsigned char VLR[], unsigned char LVR[], int n)
{
    link p;
    if (n <= 0){
        return NULL;
    }

    p = make_node(VLR[0]);
    int k = 0;
    while (VLR[0] != LVR[k]){
        ++k;
    }
    p->l = init(VLR + 1, LVR, k);
    p->r = init(VLR + k + 1, LVR + 1 + k, n - k - 1);

    return p;
}

void pre_order(link t, void (*visit) (link))
{
    if (!t)
        return;
    visit(t);
    pre_order(t->l, visit);
    pre_order(t->r, visit);
}

void in_order(link t, void (*visit) (link))
{
    if (!t)
        return;
    in_order(t->l, visit);
    visit(t);
    in_order(t->r, visit);
}

void post_order(link t, void (*visit) (link))
{   
    if (!t)
        return;
    post_order(t->l, visit);
    post_order(t->r, visit);
    visit(t);
}

int count(link t)
{
    if (!t)
        return 0;
    int l = count(t->l);
    int r = count(t->r);
    return 1 + l + r;
}

int depth(link t)
{
    if (!t)
        return 0;
    int l = depth(t->l);
    int r = depth(t->r);
    return 1 + (l > r ? l : r);
}

void destroy(link t)
{
    post_order(t, free_node);
}
